package com.jsb.shiro;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import com.jsb.model.Admin;
import com.jsb.service.AdminService;
import com.jsb.shiro.UserRealm.Principal;
@Component
public class UserUtils {
	
	private static final Logger logger = Logger.getLogger(UserUtils.class);
	
	@Resource
	private AdminService adminService;
	
	public static final String USER_CACHE = "userCache";
	public static final String USER_CACHE_ID_ = "id_";
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Object principal2 = subject.getPrincipal();
			Principal principal = (Principal)principal2;
			if (principal != null){
				return principal;
			}
//			subject.logout();
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static Admin getUser(){
		Principal principal = getPrincipal();
		logger.info("用户sessionid为："+principal.getSessionid());
		if (principal!=null){
			Admin user = get(principal.getId());
			if (user != null){
				return user;
			}
			return new Admin();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new Admin();
	}
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static Admin get(String id){
		logger.info("用户ID为:"+id);
		Admin user = (Admin)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user ==  null){
			if (user == null){
				return null;
			}
		}
		return user;
	}
	
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			logger.info("session getid 为:"+session.getId());
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
}
